methods 和 computed 和 watch方法的區(qū)別
computed是計算屬性左权,是有依賴緩存的挟鸠,只有在它的依賴發(fā)生改變時才會重新計算童太,這個計算出來的值膝晾,是可以直接當成data來用的苍鲜,在用的時候不需要添加(),computed必須要有一個return值
methods沒有依賴緩存玷犹,只要發(fā)生重新渲染混滔,methods方法總會執(zhí)行該函數(shù)
數(shù)據(jù)量大,需要緩存的時候用computed歹颓,每次確實需要重新-加載坯屿,不需要緩存 的時候使用methods
watch是Vue提供的一種更通用的方式來觀察和響應(yīng)Vue實例上的數(shù)據(jù)變動
盡量使用computed計算屬性來監(jiān)視數(shù)據(jù)的變化,因為他本身就有這個屬性巍扛,watch沒有computed自動领跛,手動設(shè)置代碼更復(fù)雜
組件
定義一個組建的配置項,一般規(guī)范是大駝峰去命名一個組件撤奸,實際上還是一個Vue實例
const HelloWorld = {
template: '<div>hello world</div>'
}
全局注冊一個組建 吠昭,就可以在任何地方使用
第一個參數(shù)是要使用的標簽名字喊括,不管是使用中線還是大駝峰,在使用組建的時候矢棚,都要使用小寫字母加中劃線
第二個參數(shù)就是組建的配置項
Vue.component('HelloWorld', HelloWorld)
局部注冊一個組件郑什,只有當前Vue實例中才能使用這些組件. 注意這里是components
<div id="app">
<h3>app</h3>
<hello-world></hello-world>
</div>
<div id="app1">
<h3>app1</h3>
<!-- 這里就報錯了,因為我把全局注冊的組件關(guān)閉了 -->
<hello-world></hello-world>
</div>
const app = new Vue({
el: '#app',
// 局部注冊一個組件蒲肋,只有當前Vue實例中才能使用這些組件. 注意這里是components
components: {
HelloWorld
},
data: {
msg: 'hello'
}
})
component-data
組件的data必須是一個方法return一個對象蘑拯,因為這樣才能保證每個組件的數(shù)據(jù)是獨立的而不是共享的
const HelloWorld = {
template: '<div>{{msg}}</div>',
data () {
return {
msg: 'hello world'
}
}
}
const app = new Vue({
el: '#app',
components: {
HelloWorld
},
data: {
msg: 'hello'
}
})
props
父組件控制子組件的值
在調(diào)用組件的時候通過text屬性綁定一個值,在組件內(nèi)部就可以通過props來接收這個值
通過props來接收調(diào)用的時候傳過來的值兜粘。一旦接收了申窘,就可以直接把props當data用,但是不能直接在內(nèi)部修改props的值孔轴。這是基于單向數(shù)據(jù)流的原則的剃法。
<div id="app">
<my-text :text="text1"></my-text>
<my-text text="world"></my-text>
<my-text text="!"></my-text>
</div>
const MyText = {
template: '<span>{{text}}</span>',
props: ['text']
}
const app = new Vue({
el: '#app',
data: {
text1: 'hello',
text2: 'world',
text3: '!'
},
components: {
MyText
}
})
如果要對傳入的props進行類型檢查,就需要使用對象的方式來寫props
如果要對x進行更多約束路鹰,就可以再把這個x寫成一個對象贷洲,里面可以有默認值,必須這些選項
props: {
x: {
//判斷屬性
type: Number,
//必傳值
required: true
},
y: {
type: Number,
//默認值
default: 0
}
}
}
props坑
<div id="app">
<!-- 由于html的屬性是忽略大小寫的悍引,所以在傳遞的時候要使用中線連接 -->
<hello hello-text="hello world!"></hello>
</div>
<script src="./vue.js"></script>
<script>
const Hello = {
template: '<div>{{helloText}}</div>',
// 由于js的命名又是駝峰類型的恩脂,所以在接收的時候又得使用駝峰
props: ['helloText']
}
如果想要通過子組件修改父組件的話,需要早子組件的按鈕點擊時間上趣斤,通過this.$emit觸發(fā)一個自定義事件
在調(diào)用這個組件的時候俩块,就通過 @事件名 這種方式去監(jiān)聽組件內(nèi)部觸發(fā)的自定義事件, 當內(nèi)部有這個自定義事件觸發(fā)的時候浓领,就會執(zhí)行app里的onChangeText方法
最終的數(shù)據(jù)修改在父組件里面
事件總線
兄弟組件玉凯,不能直接通信,需要通過事件總線實現(xiàn)通信
事件總線联贩,相當于總指揮中心, 啥都不渲染漫仆。只是一個空的vue實例
同樣通過$emit觸發(fā)事件
const bus = new Vue()