1. 组件是什么?
new Vue 接收相同的选项。2. data必须是一个函数
3. 通过 props[字符串数组] 向子组件传递数据
<!-- 父组件 -->
<container :title="mytitle"></container>
data() {
return {
mytitle: ‘my happy job‘
}
}
<!-- 子组件 -->
Vue.component(‘container‘, {
props: [‘title‘],
template: ‘<h3>{{ title }}</h3>‘
})
4. 监听子组件事件
<!-- 父组件 --> <container ... v-on:enlarge-text="postFontSize += 0.1" ></container> <!-- 子组件 --> <button v-on:click="$emit(‘enlarge-text‘)"> Enlarge text </button>
<!-- 父组件 --> <container ... v-on:enlarge-text="postFontSize += $event" ></container> <!-- 子组件 --> <button v-on:click="$emit(‘enlarge-text‘, 0.1)"> Enlarge text </button>
<!-- 父组件 -->
<container
...
v-on:enlarge-text="onEnlargeText"
></container>
methods: {
onEnlargeText: function (enlargeAmount) {
this.postFontSize += enlargeAmount
}
}
<!-- 子组件 -->
<button v-on:click="$emit(‘enlarge-text‘, 0.1)">
Enlarge text
</button>
<!-- 父组件 -->
<container v-model="searchText"></container>
<container
v-bind:value="searchText"
v-on:input="searchText = $event"
></container>
<!-- 子组件 -->
Vue.component(‘container‘, {
model: {
prop: ‘checked‘,
event: ‘change‘
},
props: [‘checked‘],
template: `
<input
type="checkbox"
v-bind:checked="checked"
v-on:input="$emit(‘change‘, $event.target.checked)"
>
`
})
5. 单文件组件 -- 高内聚,低耦合。易维护
优点:完整语法高亮;commonJS模块;组件作用域的css
<template>
<div class="container"></div>
</template>
<script>
export default {
name: ‘cointainer‘,
data() {
return {
}
}
}
</script>
<style>
</style>
6. prop
props: [‘initialCounter‘],
data: function () {
return {
counter: this.initialCounter
}
}
props: [‘size‘],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
7. 自定义事件
原文:https://www.cnblogs.com/pleaseAnswer/p/13324165.html