【发布时间】:2020-09-11 13:17:43
【问题描述】:
我确定这些信息在某个地方,但我整个下午都在谷歌上搜索,无法以一种能够让我理解所需的方式来表达我的问题。我想在我的 Vue 实例中编写一个方法,并在我使用路由显示的模板中使用它。以下是部分代码:
const Home = { template:
'<div class="container">' +
'I\'m leaving some stuff out, but routing works fine in the real code' +
'</div>'
};
const Level = { template:
'<div class="container">' +
'<h2>Level {{ id }}</h2>' +
'{{ say_hello }}' +
'</div>',
props: ['id','say_hello']
}
// === Define our routes ===
const router = new VueRouter({
routes: [
{ path: '/', component: Home, props: true },
{ path: '/level/:id', component: Level, props: true }
]
})
// === Now fire up Vue and display it on screen ===
const vm = new Vue({
el: '#app',
router,
template: '<router-view></router-view><p><router-link to="/level/1">Level 1</router-link></p>',
methods: {
say_hello: function() {
return 'hello';
}
}
})
我意识到这有点乱,但在完整的代码中,除了我的 '{{ say_hello }}' 永远无法工作,无论我尝试什么,它都可以正常工作。我基本上总是收到各种“未定义”或“不是函数”的错误消息。我的猜测是,无论出于何种原因,该方法都无法通过路由器,但我无法弄清楚要修复什么才能使其正常工作。
感谢您的帮助!
编辑:我刚刚意识到这基本上是我几周前问的一个问题的变体,我从来没有真正得到答案来帮助我找出问题(几个答案,但没有一个对我有用)。上次我使用全局变量回避了这个问题。我真的很想弄清楚这实际上是如何工作的!上一个问题:Vue computed property in router template
【问题讨论】:
-
您已将
say_hello设置为Level组件中的道具,但您从未向其中传递任何内容。你想从你的say_hello方法传递返回值还是你想让你的Level组件以某种方式执行say_hello方法? -
在Level组件中,我想将
{{ say_hello }}替换成“hello”这个词。
标签: javascript vue.js vue-router