export default new Router({ routes: [ { path: '/paramsPassingByRouter', component: ParamsPassingByRouter, children: [ { path: 'paramsMode', name: 'paramsMode', component: ParamsMode } ] } ] })
<!-- html --> <button @click="paramsMode(testData)">params傳參</button> <!-- js --> <script> export default { data () { return { testData: { id: '20180101', name: '張三', aka: 'z3', age: '18' } } }, methods: { paramsMode (data) { this.$router.push({ name: 'paramsMode', params: data }) } } } </script>
<!-- html --> <div class="params-mode">{{ testData }}</div> <!-- js --> <script> export default { data () { return { testData: {} } }, created () { this.testData = this.$route.params } } </script>
url:http://localhost:8081/#/paramsPassingByRouter/paramsMode
頁面顯示:{"id":"20180101","name":"張三","aka":"z3","age":"18"} html
可是刷新頁面後,數據會丟失,顯示:{}。vue
export default new Router({ routes: [ { path: '/paramsPassingByRouter', component: ParamsPassingByRouter, children: [ { path: 'queryMode', name: 'queryMode', component: QueryMode } ] } ] })
<!-- html --> <button @click="queryMode(testData)">query傳參</button> <!-- js --> <script> export default { data () { return { testData: { id: '20180101', name: '張三', aka: 'z3', age: '18' } } }, methods: { queryMode (data) { this.$router.push({ name: 'paramsMode', query: data }) } } } </script>
<!-- html --> <div class="query-mode">{{ testData }}</div> <!-- js --> <script> export default { data () { return { testData: {} } }, created () { this.testData = this.$route.query } } </script>
url:http://localhost:8081/#/paramsPassingByRouter/queryMode?id=20180101&name=%E5%BC%A0%E4%B8%89&aka=z3&age=18
頁面顯示:{"id":"20180101","name":"張三","aka":"z3","age":"18"} this
刷新頁面後,數據不會丟失。url
使用 this.$router.push({ name: '模塊名稱', query: { // 各參數 } })
方式傳參。code
缺點:參數值都拼接在 url 上,url 會很長,同時均可被看到。
this.$router.push({ name: '模塊名稱', params: { // 各參數 } })
路由文件設置的時候把參數拼到 url 裏。component
url: http://localhost:8081/#/paramsPassingByRouter/paramsMode/20180101/%E5%BC%A0%E4%B8%89/z3/18
缺點:同上。
this.$router.push({ name: '模塊名稱', params: { // 各參數 }, query: { // 各參數 } })
。老老實實的用 localStorage 存儲。router
url: http://localhost:8081/#/paramsPassingByRouter/paramsMode/z3
能夠與 params 和 query 方式配合使用,能夠暴露的參數顯示在 url 上,同時刷新參數也不會丟失。
銷燬頁面的時候把 localStorage 存儲的內容清除。
// router.js { path: 'paramsMode/:aka', name: 'paramsMode', component: ParamsMode } <!-- ParamsMode.vue 修改 --> <script> export default { data () { return { testData: {} } }, created () { const tempData = localStorage.getItem('tempData') if (tempData) { this.testData = JSON.parse(tempData) } else { this.testData = this.$route.params localStorage.setItem('tempData', JSON.stringify(this.$route.params)) } }, beforeDestroy () { localStorage.removeItem('tempData') } } </script>