Vue组件

组件

// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

组件是可复用的 Vue 实例,且带有一个名字:在这个例子中是 。我们可以在一个通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用:

<div id="components-demo">
  <button-counter></button-counter>
</div>
new Vue({ el: '#components-demo' })

因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。

App.vue

  • <template></template> 用来表示组件的结构
  • <script></script> 用来编写组件的逻辑
  • <style></style> 用来表示组件的样式

template

<template>
  <!-- 组件的结构 -->
  <div id="app">
    <Vheader :title="msg"></Vheader>
    <Vcontent :menu="menu"></Vcontent>
  </div>

</template>

script

 //组件的逻辑
  export default{    //对外输出本模块
  name:"App",        //对外显示的组件名
  data(){           //data必须是一个函数
      return {
        msg:"hello Vue",
        menu:["C","C#","C++"]
    }
  },
  components:{
    Vheader,
    Vcontent
  }

}

style

<style>
  /* 全局组件的样式 */

</style>

/* 仅会在本组件有效 */
<style scoped>
	*{
		color:red;
	}
</style>

解耦

样式

重用组件

<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

通过Prop父组件向子组件传值

通过Prop向子组件传值
Prop 是你可以在组件上注册的一些自定义特性。当一个值传递给一个 prop 特性的时候,它就变成了那个组件实例的一个属性。

<Vheader :title="msg"></Vheader>

我们在Vheader上自定义注册了一个title属性,我们在App.vue的data中指定了msg的值。msg->title就变成了Vheader实例的一个属性。

在子组件中:我们可以用一个 props 选项将其包含在该组件可接受的 prop 列表中
一个组件默认可以拥有任意数量的prop
任何值都可以传递给任何 prop
我们能够在 组件实例中访问这个值,就像访问 data 中的值一样。

props:{
    title:String,
}

通过事件子组件向父组件传值

我们可以调用内建的 $emit 方法并传入事件的名字,来向父级组件触发一个事件.

<button v-on:click="$emit('enlarge-text')">
  Enlarge text
</button>

然后我们可以用 v-on 在父组件上监听这个事件,就像监听一个原生 DOM 事件一样:

<blog-post
  ...
  v-on:enlarge-text="postFontSize += 0.1"
></blog-post>
原文地址:https://www.cnblogs.com/weihengblog/p/9235945.html