Vue使用平時總結知識點
目錄:
router
vue2.0中的$router 和 $route的區別
自己總結:
$router
是路由管理器(管理所有$route
並實現跳轉功能) $route
是每個路由對象,包含當前路由的所有元數據
router
router是VueRouter的一個對象,通過Vue.use(VueRouter)和VueRouter構造函數得到一個router的實例對象,這個對象中是一個全局的對象,他包含了所有的路由包含了許多關鍵的對象和屬性。
舉例:history對象
$router.push({path:‘home’});本質是向history棧中添加一個路由,在我們看來是 切換路由,但本質是在添加一個history記錄
方法:
$router.replace({path:‘home’});//替換路由,沒有歷史記錄
route
route是一個跳轉的路由對象,每一個路由都會有一個route對象,是一個局部的對象,可以獲取對應的name,path,params,query等
- $route.path
字符串,等於當前路由對象的路徑,會被解析爲絕對路徑,如 “/home/news” 。 - $route.params
對象,包含路由中的動態片段和全匹配片段的鍵值對 - route.query.favorite == ‘yes’ 。
- $route.router
路由規則所屬的路由器(以及其所屬的組件)。 - $route.matched
數組,包含當前匹配的路徑中所包含的所有片段所對應的配置參數對象。 - $route.name
當前路徑的名字,如果沒有使用具名路徑,則名字爲空。 - $route.path, $route.params, $route.name, $route.query這幾個屬性很容易理解,看示例就能知道它們代表的含義
導航守衛者
router.beforeEach((to, from, next) => {
//to 是route from 也是route 對象
})
Vue.use() 引入組件 和 Vue.component() 引入區別
- 我是這麼理解:Vue.component() 是基礎方法,所有組件都會調用類似方法
- Vue.use() 爲什麼誕生
現在有這個需求,某些組件 是混合其他三方組件,在加載的時候,需要需要處理一些邏輯,我們可以在Vue.component()
時候自己處理 ,現在這樣組件有一個可以這麼幹,有兩個,三個,或者更多了,就不太友好了 - Vue.use() 很類似Java後臺訪問者模式
通過install方法把Vue引用傳入到自己組件裏面,然後在自己組件,執行一些初始化的操作,然後在執行Vue.component()
然後執行Vue.use(),方法的時候,會執行組件的 install方法
注意: 以上是個人理解,請帶着批判眼光看,如果有不對,請不吝賜教
Vue $root $parent $refs 三者的區別和作用
作用:
$parent 父組件對象
$root 根組件對象
$refs 獲取子組件對象
例子:
<!doctype html>
<html>
<head>
</head>
<body>
<div id ='app'>
<div>
{{ message }}
</div>
<test ref = 't1'></test>
</div>
</body>
<script src="http://t.cn/RdgHJHU"></script>
<script>
var test1 = {
name: 'test1',
data(){
return {
myMessage:this.$root.$data.message,
myOne:this.$parent.$data.one
}
},
template:'<div>I am child one{{myMessage}} ,{{myOne}}</div>'
};
var test = {
name: 'test',
components:{
'test1':test1
},
data(){
return {
one: 'one'
}
},
template:'<div>test<test1></test1></div>'
};
var vue = new Vue({
el: '#app',
components:{
'test': test
},
data(){
return {message: 'hello world'}
}
});
console.log('vue',vue);
console.log('refs',vue.$refs);
console.log('parent',vue.$parent.t1);
console.log('root',vue.$root);
</script>
</html>
vue @click.native.prevent 爲什麼要加native
組件上調用事件的時候必須加 native,因爲是組件非div
@click.prevent @click.stop 區別
@click.stop 阻止事件冒泡
@click.prevent 阻止事件的默認行爲,
@keyup.enter
//按下enter時,執行方法test7
<input type=“text” @keyup.enter=“test7”>