vue學習十五(props解耦、props 布林-物件-函式三種模式)
阿新 • • 發佈:2018-12-14
$route耦合
在元件中使用 $route 會使之與其對應路由形成高度耦合,從而使元件只能在某些特定的 URL 上使用,限制了其靈活性。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> <script src="https://unpkg.com/
[email protected]/dist/vue-router.js"></script> </head> <body> <div id="box"> <router-link to="/one/1">One</router-link> <router-view></router-view> </div> <!--定義模版--> <template id="Foo"> <div> 第一個router {{$route.params.id}} </div> </template> <script> //1、定義 (路由) 模版元件 //2、定義路由 var routes = [ { path: "/one/:id", component: { template: "#Foo" }, props: true } ]; // 3、建立 router 例項 var router = new VueRouter({ routes }); // 4、建立和掛載根例項 const app = new Vue({ router }).$mount('#box') </script> </body> </html>
瀏覽器輸入file:///Users/zhiliao/zhiliao/vue/index_test.html#/one/1
輸出如下:
One
第一個router 1
props解耦
props 布林模式
如果 props 被設定為 true,route.params 將會被設定為元件屬性。
<body> <div id="box"> <router-link to="/one/1">One</router-link> <router-view></router-view> </div> <!--定義模版--> <template id="Foo"> <div> {{id}} </div> </template> <script> const Foo = { props: ['id'], template: "#Foo", } //1、定義 (路由) 模版元件 //2、定義路由 var routes = [ { path: "/one/:id", component: Foo, props: true } ]; // 3、建立 router 例項 var router = new VueRouter({ routes }); // 4、建立和掛載根例項 const app = new Vue({ router }).$mount('#box') </script> </body>
測試結果如下:
file:///Users/zhiliao/zhiliao/vue/index_test.html#/one/1
瀏覽器輸出如下:
One
1
props物件模式
<body>
<div id="box">
<router-link to="/one/1">One</router-link>
<router-view></router-view>
</div>
<!--定義模版-->
<template id="Foo">
<div>
{{userName}}
</div>
</template>
<script>
const Foo = {
props: ['userName'],
template: "#Foo",
}
//1、定義 (路由) 模版元件
//2、定義路由
var routes = [
{
path: "/one/:id",
component: Foo,
props:{
userName: 'mapbar_front'
}
}
];
// 3、建立 router 例項
var router = new VueRouter({
routes
});
// 4、建立和掛載根例項
const app = new Vue({
router
}).$mount('#box')
</script>
</body>
瀏覽器效果如下:
file:///Users/zhiliao/zhiliao/vue/index_test.html#/one/1
瀏覽器渲染如下:
One
mapbar_front
props函式模式
你可以建立一個函式返回 props。這樣你便可以將引數轉換成另一種型別,將靜態值與基於路由的值結合等等。
<body>
<div id="box">
<router-link to="/one/1">One</router-link>
<router-view></router-view>
</div>
<!--定義模版-->
<template id="Foo">
<div>
{{userName}}
{{id}}
</div>
</template>
<script>
const Foo = {
props: ['userName',"id"],
template: "#Foo",
}
//1、定義 (路由) 模版元件
//2、定義路由
var routes = [
{
path: "/one/:id",
component: Foo,
// props:{
// userName: 'mapbar_front'
// },
props: (route) => (
{
userName: "mapbar_front",
id: route.params.id
}
)
}
];
// 3、建立 router 例項
var router = new VueRouter({
routes
});
// 4、建立和掛載根例項
const app = new Vue({
router
}).$mount('#box')
</script>
</body>
瀏覽器輸入
file:///Users/zhiliao/zhiliao/vue/index_test.html#/one/1
效果輸出如下:
One
mapbar_front 1