父子组件,及组件的分离写法

初学vue,关于组件的写法习惯于写在一起,怎么方便怎么来,一直觉得有问题,但是找不到较好的模板

最近看一

大佬的博客

分析其代码中关于组件的写法,特此记录

代码如下:

<div id="example">
  <parent></parent>
</div>
<script>
var childNode = {
  template: `<button @click="incrementCounter">{{ counter }}</button>`,
  data(){
    return {
      counter: 0
    }
  },
  methods:{
    incrementCounter(){
      this.counter ++;
      this.$emit('increment');
    }
  },
}
var parentNode = {
  template: `
  <div class="parent">
    <p>{{total}}</p>
    <child @increment="incrementTotal"></child>
    <child @increment="incrementTotal"></child>
  </div>
  `,
  components: {
    'child': childNode
  },
  data(){
    return {
      'total':0
    }
  },
  methods:{
    incrementTotal(){
      this.total ++;
    }
  }
};
// 创建根实例
new Vue({
  el: '#example',
  components: {
    'parent': parentNode
  }
})
</script>

将代码分成4部分如下所示:

1是一个vue的实例,简单的el绑定后,就是一个组件注册(父组件),组建中并没有写template,props,methods等等,而是将其都集成到一个父节点中去

2是父节点,它包括了父组件的所有东西,同时还在父组件中注册了一个子组件,与父组件一样,子组件中也只包含一个子节点,

子组件中的具体都在子节点中实现了

右下角是在html中以标签的形式使用定义的父组件,由于嵌套的原因,子组件也会运行

 

posted on 2018-06-14 16:00  xiaoxiaoyao61  阅读(539)  评论(0编辑  收藏  举报

导航