vue组件知识点

1、组件的定义
const component = {
  props: {  //外部父组件约束子组件的 里面不要修改 可以通过触发事件来修改
    active: Boolean,
    propOne: String,
    onChange: Function
  },
  template: '<div @click="handleChange">this is component <span>{{propOne}}</span> <span v-show="active">see me if active</span></div>',
  data: function () {  //用function 避免下面问题
    return {    //return 这个对象不能是全局的不然重复使用会修改全局的text
      text: 123
    }
  },
  methods: {
    handleChange: function () {
      this.onChange() //调用props上的onChange this.$emit('change') <comp-one :prop-one="prop" @change="handler"></comp-one>
    }
  }
}

new Vue({  //new vue 就是一个组件
template: '<div>123 <comp-one :prop-one="prop" :on-change="handler"></comp-one> <comp-one :active="true"></comp-one></div>',
el: '#app',
data: {
  prop: 'text1'
},
methods: {
  handler: function () {
    this.prop = 'text2'
  }
},
components: {  //注册vue实例下的组件
  CompOne: component
}
})
 
 
//Vue.component('CompOne',component)  ////全局注册组件 
 
 
2、extend
 
const CompVue = Vue.extend(component)
new CompVue({
  el:'#root'
})
 
this.$parent  可以修改父组件的data里面的东西
 
3、插槽
 
const component = {
  template: '<div :style="style"><div class="header"><slot name="header"></slot></div>this is component</div>',
  data: function () { 
    return { 
      style: {
        width:"200px",
        height:"200px",
        border:"1px solid #aaa"
      }
    }
  }
}
 
 
new Vue({
  components:{
    CompOne:component
  },
  template:'
    <div><comp-one><span slot="header"></span></comp-one></div>
  '
})

猜你喜欢

转载自www.cnblogs.com/suanmei/p/9318857.html