Vue 组件
组件开发模式下,我们的页面就是一堆component组件按照逻辑关系堆砌出来的,组件是Vue非常用特色的功能之一,组件都是模块化开发,组件实例之间的作用域是相互独立的。
所有的vue.js组件都是扩展的vue实例
var MyComponent = Vue.extend({ //扩展选项对象 }) var myComponentInstance = new MyComponent();
首先认识下父子组件:
情况1、
// HTML
<div id="example"> <my-component></my-component> </div> // 定义 var MyComponent = Vue.extend({ template: '<div>A custom component!</div>' }) // 注册 Vue.component('my-component', MyComponent)
// 创建根实例 new Vue({ el: '#example' }) // 结果: <div id="example"> <div>A custom component!</div> </div>
情况2、
父组件通过import的方式导入子组件,并在components属性中完成注册,然后子组件就可以通过child的形式嵌进父组件。
组件注册
// HTML
<template> <div> <h1>我是父组件!</h1> <child></child> </div> </template> <script> import Child from '../components/child.vue'
// 创建实例 export default { ...
// 组件注册 components: {Child}, ... } </script>
组件定义
<template> <h3>我是子组件!</h3> </template> <script> </script>
子组件的使用方式有上边两种情形。
父子组件之间的交互
一、从父组件见到子组件
1、父子组件通信时,父组件通过vue动态传值传递数据,子组件通过prop选项单项绑定,从父组件接受数据传递。
2、通过ref用在子组件上,指向的是组件实例,可以理解为子组件的索引,通过$ref可以获取到组件里的属性和方法
<template> <div> <h1>我是父组件!</h1> <child ref="msg"></child> </div> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, mounted: function () { console.log( this.$refs.msg); this.$refs.msg.getMessage('我是子组件一!') } } </script>
<template> <h3>{{message}}</h3> </template> <script> export default { data(){ return{ message:'我是子组件' } }, methods:{ getMessage(m){ this.message=m; } } } </script>
从上边的代码我们可以发现,通过ref="msg"可以将子组件child的实例指给$ref,并且通过msg.getMessage()调用到子组件的getMessage方法,将参数传递给子组件。
prop 着重于数据的传递,它并不能调用子组件里的属性和方法;
$ref 着重于索引,主要用来调用子组件的属性和方法,并不擅长数据传递,而且ref用在dom元素的时候,它能起到选择器的作用,这个功能比作为索引更常有用到。
二、从子组件到父组件
1、父子组件通信是,子组件通过$emit触发父组件的方法,完成数据交互。
<template> <div> <h1>{{title}}</h1> <child @getMessage="showMsg"></child> </div> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, data(){ return{ title:'' } }, methods:{ showMsg(title){ this.title=title; } } } </script>
<template> <h3>我是子组件!</h3> </template> <script> export default { mounted: function () { this.$emit('getMessage', '我是父组件!') } } </script>