vue 组件及动态组件

vue版本:1.0.28

需要注意的是:

组件中的数据data是一个函数对象  必须return一个json对象

js

var Home=Vue.extend({
     data(){
          return {
                msg:"我是Home组件"
          }
     },
     mthods:{
          change(){
              this.msg="我是home组件->welcome vue!"
          }
     },
     template:'<h3 @click="change">{{msg}}</h3>'     
}) 

Vue.component('home',Home);//第一种方法(全局组件)
Vue.component('news',{//第二种方法(全局组件)
  data(){
    return {
      msg:"我是news组件"
}
  },
  template:<h3>{{msg}}<h3>
})

var Login=Vue.extend({
  data(){
    return {
      msg:"我是注册组件"
    }
  },
  template:'#login'
})
var vm=new Vue({
  el:
'#wrap', data:{}, methods:{},
  components:{
    "login":Login,//第三种方法(局部组件)
    "reg":{//第四种方法(局部组件)
      data(){
        return {
          msg:"我是注册页面"
        }
      },
      template:"#reg"
    }
  }  })

html

<div id="wrap">
   <home></home>
  <news></news>
  <login></login>
  <reg></reg> </div>

<template id="login"> 
  <h3>{{msg}}</h3>
</template>

<template id="reg">
  <h3>{{msg}}</h3>
</template>

 

动态组件

html:

<div id="box">
  <input type="button" value="按钮" @click="toggle">
  <component :is="a"></component> </div>

<template id="home">
  <h3>{{msg}}</h3>
</template>

<template id="news">
  <h3>{{msg}}</h3>
</template>
<script>  

  window.onload=function(){
    var vm=new Vue({
       el:"#box",
       data:{
         a:"home"
       },
       methods:{
         toggle(){
          if(this.a=="home"){
            this.a="news";
          }else{
            this.a="home";
          }
         }
       },
       components:{
        "home":{
          data(){
            return {
              msg:"我是主页内容"
            }
          },
          methods:{},
          template:"#home"
        },
        "news":{
          data(){
            return {
              msg:"我是新闻内容"
            }
          },
          template:"#news"
        }  
       }
    })
  } </script>

 

以上只是个人的笔记记录  如有错误欢迎指出

 

posted @ 2018-07-12 11:27  juneChen  阅读(349)  评论(0编辑  收藏  举报