- 每一个组件都是一个vue实例
- 每个组件均具有自身的模板template,根组件的模板就是挂载点
- 每个组件模板只能拥有一个根标签
- 子组件的数据具有作用域,以达到组件的复用
| <div id="app"> |
| <h1>{{ msg }}</h1> |
| </div> |
| <script type="text/javascript"> |
| |
| |
| var app = new Vue({ |
| |
| el: "#app", |
| data : { |
| msg: "根组件" |
| }, |
| |
| |
| template: "<div>显式模板</div>" |
| }) |
| |
| </script> |
| <div id="app"> |
| <local-tag></local-tag> |
| <local-tag></local-tag> |
| </div> |
| <script> |
| var localTag = { |
| data () { |
| return { |
| count: 0 |
| } |
| }, |
| template: '<button @click="btnAction">局部{{ count }}</button>', |
| methods: { |
| btnAction () { |
| this.count ++ |
| } |
| } |
| } |
| new Vue({ |
| el: "#app", |
| components: { |
| 'local-tag': localTag |
| } |
| }) |
| </script> |
| <div id="app"> |
| <global-tag></global-tag> |
| <global-tag></global-tag> |
| </div> |
| <script> |
| Vue.component('global-tag', { |
| data () { |
| return { |
| count: 0 |
| } |
| }, |
| template: '<button @click="btnAction">全局{{ count }}</button>', |
| methods: { |
| btnAction () { |
| this.count ++ |
| } |
| } |
| }) |
| new Vue({ |
| el: "#app" |
| }) |
| </script> |
| <div id="app"> |
| <global-tag :sup_data1='sup_data1' :supData2='sup_data2'></global-tag> |
| </div> |
| <script type="text/javascript"> |
| Vue.component('global-tag', { |
| props:['sup_data1', 'supdata2'], |
| template: '<div>{{ sup_data1 }} {{ supdata2 }}</div>' |
| }) |
| new Vue({ |
| el: '#app', |
| data: { |
| sup_data1: '数据1', |
| sup_data2: '数据2' |
| } |
| }) |
| </script> |
| <div id="app"> |
| <global-tag @send_action='receiveAction'></global-tag> |
| </div> |
| <script type="text/javascript"> |
| Vue.component('global-tag', { |
| data () { |
| return { |
| sub_data1: "数据1", |
| sub_data2: '数据2' |
| } |
| }, |
| template: '<div @click="clickAction">发生</div>', |
| methods: { |
| clickAction () { |
| this.$emit('send_action', this.sub_data1, this.sub_data2) |
| } |
| } |
| }) |
| new Vue({ |
| el: '#app', |
| methods: { |
| receiveAction (v1, v2) { |
| console.log(v1, v2) |
| } |
| } |
| }) |
| </script> |
| <div id="app"> |
| <div> |
| <input type="text" v-model="val"> |
| <button type="button" @click="submitMsg">提交</button> |
| </div> |
| <ul> |
| |
| <todo-list v-for="(v, i) in list" :key="i" :v="v" :i="i" @delect_action="delect_action"></todo-list> |
| </ul> |
| </div> |
| <script type="text/javascript"> |
| Vue.component("todo-list", { |
| template: "<li @click='delect_action'><span>第{{ i + 1 }}条: </span><span>{{ v }}</span></li>", |
| props: ['v', 'i'], |
| methods: { |
| delect_action () { |
| this.$emit("delect_action", this.i) |
| } |
| } |
| }) |
| |
| new Vue({ |
| el: "#app", |
| data: { |
| val: "", |
| list: [] |
| }, |
| methods: { |
| submitMsg () { |
| |
| if (this.val) { |
| this.list.push(this.val); |
| this.val = "" |
| } |
| }, |
| delect_action(index) { |
| this.list.splice(index, 1) |
| } |
| } |
| }) |
| </script> |