我有一些文字试图根据路线名称更改样式。我设置了2个路线名称,广告和网站,并设置了观察者来观察路线。如果路由名称是广告或网站,则我希望文本具有color:white;background-color:orange
。但是我不确定该怎么做。
new Vue({
el: '#app',
data() {
return {
styleClass: null
}
},
watch: {
'$route' (to, from) {
if (to.name == 'ads' || to.name == 'webs') {
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<div id="app">
<span><h1>Hello!!!</h1></span>
</div>
答案 0 :(得分:1)
我将创建一个计算属性来表示当前路线是否符合您的条件。
computed: {
highlight () {
return this.$route.matched.some(({ name }) => /^(ad|web)s$/.test(name))
}
}
然后您可以在class
绑定表达式中使用它。
<span :class="{ highlight }">Text goes here</span>
以及您的CSS
.highlight {
color: white;
background-color: orange;
}
有关matched
属性的信息,请参见https://router.vuejs.org/api/#route-object-properties。
答案 1 :(得分:0)
我想您缺少路由vuejs插件,并且也将您的应用程序命名为路由名称。这里是完整的例子。希望你得到想要的东西
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const routes = [
{ path: '/foo', component: Foo, name: 'ads' },
{ path: '/bar', component: Bar, name: 'nowebs' }
]
const router = new VueRouter({
routes
})
const app = new Vue({
router,
data() {
return {
styleClass: null
}
},
watch: {
'$route' (to, from) {
if (to.name == 'ads' || to.name == 'webs') {
this.styleClass = "color:white;background-color:orange"
} else {
this.styleClass = ""
}
}
}
}).$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<div id="app">
<span><h1 :style="styleClass">Hello!!!</h1></span>
<p>
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<router-view></router-view>
</div>