vue.js - 路由更改时如何更新我的 Vue 组件?
问题描述
我有一个组件:
<template>
<ul class="nav nav-pills nav-fill fixed-bottom">
<li class="nav-item">
<router-link to="/app">
<a class="nav-link active" href="/app">
<i class="material-icons md-48">view_list</i>
</a>
</router-link>
</li>
...
</ul>
</template>
<script>
export default {
name: "Navigation"
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.nav {
background: white;
border-top: 0.1px solid silver;
}
.nav-pills .nav-link {
border-radius: 0;
}
</style>
组件如何知道路径何时发生变化以及当前路由是什么?
解决方案
我使用 vuex 做了一个简单的例子,但它解释了@Sumurai8 所说的。我唯一没有添加的是:key
销毁组件。
你可以在这里试试
const Navigation = {
template: '#navigation',
data: function() {
return {
oldRoute: null
}
},
computed: {
myRoute: function() {
return this.$route.path
}
},
watch: {
'$route.path': function(newVal, oldVal) {
this.oldRoute = oldVal
}
}
};
const Home = {
template: '#home',
}
const Component1 = {
template: '#component1'
};
const Component2 = {
template: '#component2'
};
const routes = [{
path: '',
component: Home
},
{
path: '/1',
component: Component1
},
{
path: '/2',
component: Component2
}
]
const router = new VueRouter({
routes
});
Vue.component('Navigation', Navigation)
new Vue({
router
}).$mount('#app');
#app {
max-width: 850px;
margin: 20px auto;
text-align: center;
}
ul>li {
display: inline-block;
margin-right: 20px;
}
.wrapper {
display: flex;
justify-content: space-between;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.7/vue-router.min.js"></script>
<script type="text/x-template" id="home">
<div>
<h2>Home</h2>
<ul>
<li>
<router-link to="/1">Component 1</router-link>
</li>
<li>
<router-link to="/2">Component 2</router-link>
</li>
</ul>
</div>
</script>
<script type="text/x-template" id="component1">
<div>
<h2>Component 1</h2>
<ul>
<router-link to="/">Home</router-link>
</ul>
</div>
</script>
<script type="text/x-template" id="component2">
<div>
<h2>Component 2</h2>
<ul>
<li>
<router-link to="/">Home</router-link>
</li>
</ul>
</div>
</script>
<script type="text/x-template" id="navigation">
<div>
<div> <strong>my route is:</strong> {{myRoute}}</div>
<div> <strong>old route:</strong> {{oldRoute}}</div>
</div>
</script>
<div id="app">
<div class="wrapper">
<h1>Basic Vue-Router</h1>
<Navigation />
</div>
<router-view></router-view>
</div>
推荐阅读
- google-sheets - 动态地对每行中的 5 个最大数字求和
- javascript - 添加时间类型的输入值 -html
- angular - 如何为数据绑定应用管道?
- angular - 带有 Angular 的离子警报 canDeactivate
- python - python prints document{} when try to iterate over xml and print tags and attributes
- python - 将文件复制到远程服务器并将其加载到 MySQL 数据库中
- c - 代码的执行接受输入但不返回任何内容
- python - 在python的数组中查找学分最高和最低的学生
- javascript - Eslint 正在从终端工作,但在编辑器 UI (VSCode) 中未显示错误
- java - 如何从当前语言环境中获取日期时间格式字符串,作为 SimpleDateFormat 的参数