一篇文章弄懂vue.js中的组件

2020-03-11  本文已影响0人  缺月楼

组件的使用方法

1.全局注册

Vue.component('my-component',{
template:'<div>我是组件的内容</div>'
})
优点:所有的nue实例都可以用
缺点:权限太大,容错率降低

2.局部注册

var app = new Vue({
el:'#app',
components:{
'my-component':{
template: '<div>我是组件的内容</div>'
}
}
})

自定义事件—子组件给父组件传递数据

使用v­on 除了监昕 DOM 事件外,还可以用于组件之间的自定义事件。
JavaScript 的设计模式 一一观察者模式, dispatchEvent 和 addEventListener这两个方法。
Vue 组件也有与之类似的一套模式,子组件用emit()来 触发事件 ,父组件用on()来 监昕子组件的事件 。

第一步:自定义事件
第二步: 在子组件中用$emit触发事件,第一个参数是事件名,后边的参数是要传递的数据
第三步:在自定义事件中用一个参数来接受

<div id="app">
    您现在的银行卡余额是{{total}}
    <son-component @change="handletotal"></son-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
  //全局 注册  需求 通过加号 按钮 和减号按钮 来给父组件传递数据
  // 第一步:自定义事件
  Vue.component('son-component', {
    "template": '<div>  <button @click="handleincrease">+1000</button>\n' +
      '<button @click="handlereduce">-10000</button> </div>',
    data: function () {
      return {
        count: 1000
      }
    },
    methods: {
      handleincrease: function () {
        this.count += 1000;
        // 第二步在子组件中用$emit触发事件,第一个参数是事件名,后边的参数是要传递的数据
        this.$emit('change', this.count)
      },
      handlereduce: function () {
        if (this.count === 0) { } else {
          this.count -= 1000;
          // 在子组件中用$emit触发事件,第一个参数是事件名,后边的参数是要传递的数据
          this.$emit('change', this.count)
        }

      }
    }
  })
  var app = new Vue({
    el: '#app',
    //局部注册x
    data: {
      total: 1000
    },
    methods: {
      // 第三步在自定义事件中用一个参数来接受
      handletotal: function (value) {
        this.total = value
      }
    }
  })
</script>
上一篇 下一篇

猜你喜欢

热点阅读