解決在vue+webpack開發中出現兩個或多個菜單公用一個組件問題,vuewebpack
在vue的實際開發中往往會遇到公用一個組件的問題,比如有一個菜單中的兩個按鈕,點擊每個按鈕調用的是同一個組件,其內容是根據路由的參數的不同來請求不同的內容。
第一步,首先建立一個vue+webpack+vuecli的demo,如下操作:
全域安裝vue-cli,vue-cil是vue的腳手架工具,安裝命令:
npm install -g vue-cli
第二步,進入到工程目錄中,建立一個vuedemo的檔案夾工程,如下兩步操作:
cd vue_test_project //進入vue_test_project目錄下vue init webpack vuedemo //在vue_test_project目錄下建立一個vuedemo工程
輸入這個命令之後,會出現一些提示,是什麼不用管,一直按斷行符號即可。
第三步,如下操作:
cd vuedemonpm install
執行npm install需要一點時間,因為會從伺服器上下載代碼啦之類的。並且在執行過程中會有一些警告資訊。不用管,等著就是了。如果長時間沒有響應,就ctrl+c停止掉,然後再執行一次即可。
最後一步,操作如下:
npm run dev
在運行了npm run dev之後,會自動開啟一個瀏覽器視窗,就可以看到實際的效果了。這個demo就建立好了。現在就在這個demo中添加一些內容,修改成如下:
修改HelloWorld.vue的內容為如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <h2>Essential Links</h2> <div class="btn"> <router-link :to="{name:'content',params:{differId:'con1'}}">內容按鈕1</router-link> <router-link :to="{name:'content',params:{differId:'con2'}}">內容按鈕2</router-link> </div> <router-view></router-view> </div></template><script>export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }}</script><style scoped>h1, h2 { font-weight: normal;}ul { list-style-type: none; padding: 0;}li { display: inline-block; margin: 0 10px;}a { color: #42b983;}</style>
路由router下的index.html的修改為如下:
import Vue from 'vue'import Router from 'vue-router'import HelloWorld from '@/components/HelloWorld'import content from '@/components/conDetail'Vue.use(Router)export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld, children:[ {name:'content',path:'content/:differId',component:content} ] } ]})
現在建立一個conDetail.vue了,如下:
<template> <div class="same"> 這個是相同的內容 <div class="conlist"> <template v-for="item in items"> <p>{{item.con}}</p> </template> </div> </div></template><script>export default { name: 'conDetail', data () { return { msg: '', differIdType:'', conlist:[ {'con':'這是第一個內容按鈕的內容1'}, {'con':'這是第一個內容按鈕的內容2'} ], items:[], } }, mounted(){ this.differIdType = this.$route.params.differId == 'con1' ? '0' : '1'; if(this.differIdType == 0){ this.items = this.conlist; }else{ this.items = []; } }, watch:{ $route:function(to,from){ this.differIdType = to.params.differId == 'con1' ? '0' : '1'; if(this.differIdType == 0){ this.items = this.conlist; }else{ this.items = []; } } }}</script><style></style>
結果就是,當點擊內容按鈕1,出現了對象的內容,點擊內容按鈕2,出現相應的內容。當然我這兒寫的是點擊按鈕2的時候,其items的內容為空白數組。這兒也使用了$route的監聽。
複用組件時,想對路由參數的變化作出響應的話,你可以簡單地 watch(監測變化) $route 對象:
const User = { template: '...', watch: { '$route' (to, from) { // 對路由變化作出響應... } }}
或者使用 2.2 中引入的 beforeRouteUpdate 守衛:
const User = { template: '...', beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() }}
總結
以上所述是小編給大家介紹的解決在vue+webpack開發中出現兩個或多個菜單公用一個組件問題,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!