前端Vue入门之路——8.组件系统

组件是可复用的 Vue 实例, 如果网页中的某一个部分需要在多个场景中使用,那么我们可以将其抽出为一个组件进行复用。组件大大提高了代码的复用率。


vue.jpg

一个典型的博客应用中,如何在子组件模板中渲染出父组件的数据:

//vue-demo.html
new Vue({
  el: '#blog-post-demo',
  data: {
    posts: [
      { id: 1, title: 'My journey with Vue' },
      { id: 2, title: 'Blogging with Vue' },
      { id: 3, title: 'Why Vue is so fun' }
    ]
  }
})
//会循环出多个blog-post

Vue.component('blog-post', {
  props: ['blogData'],
  template: `
    

{{ blogData.title }}

//富文本内容
` })
  • 一个组件的 data 选项必须是一个函数
  • 每个组件必须只有一个根元素:模板的内容包裹在一个父元素内
  • 全局注册的组件可以用在其被注册之后的任何 (通过 new Vue) 新创建的 Vue 根实例,也包括其组件树中的所有子组件的模板中

父子组件间传值

父组件传值给子组件

//parent.vue(核心代码)

data(){
return {
test:'我是父组件的数据'
}
}
//child.vue(核心代码)
props:{
 'post':String
}
template:`
接收数据:{{post}}
` //接收数据:我是父组件的数据

子组件传值给父组件

//child.vue(核心代码)
data(){
return {
test1:'我是子组件的数据'
}
}
template:`
`, methods:{ event:function(){ this.$emit('post1',this.test1) } }
//parent.vue(核心代码)

methods:{
accept:function(e){
console.log(`接收数据:${e}`)     //接收数据:我是子组件的数据
}
}

父子组件间传方法

子组件调用父组件方法

//parent.vue(核心代码)
methods:{
//声明父组件的方法
  parentFun(){
          console.log('我是父组件的方法')
      }
}
//child.vue(核心代码)
methods:{
//在子组件中调用父组件的方法
  callParent(){
        this.$parent.parentFun()
      }
}

父组件调用子组件方法

//child.vue(核心代码)
methods:{
//声明子组件的方法
  childFun(){
          console.log('我是子组件的方法')
      }
}
//parent.vue(核心代码)
template:`
//在模板中加入子组件的标识符ref
`, methods:{ //在父组件中调用子组件的方法 callChild(){ this.$refs.child1.childFun() } }

非父子组件间传值

建立一个公共的(事件总线)js文件,专门用来传递消息

//bus.js
import Vue from 'vue'
export default new Vue;

在需要传递消息的地方引入

//component.vue
import bus from './bus.js'
//发送消息
bus.$emit('showMsg',msg)
//接收消息
bus.$on('showMsg',msg=>{
console.log(msg)
})

插槽的用法

//parent.vue

Hello word//在子组件标签内声明需装载到插槽的html

//child.vue

我想说
//在子组件的模板中加入插槽渲染
哈哈
//我想说 //Hello word //哈哈

你可能感兴趣的:(前端Vue入门之路——8.组件系统)