vue 在template 写 v-for 问题

先上代码

<router-view></router-view>

const Article = {
    template:'<div>article</div>'
}

const News = {
    template:'<ul>\
                <li class="news" v-for="item in items">\
                    <div class="cover" v-bind:style="{backgroundImage:\'url(\'+item.bg+\')\'}"></div>\
                    <h4 class="title">{{ item.title }}<span class="up_time">{{ item.date }}</span></h4>\
                    <h5 class="detail">{{ item.detail }}</h5>\
                    <div class="border_bottom"></div>\
                </li>\
            </ul>\
'}

const router = new VueRouter({
    routes:[
        {path:'/article', component: Article},
        {path:'/',component: News}
    ]
})

var box = new Vue({
    router,
    el: "#box",
    data: {
    items: []    
    },
    ...

代码大概就是这样,想通过vue-router判断不同路径在router-view中渲染不同内容,但是像上面这么写会报错:

[Vue warn]: Property or method "items" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. 
(found in anonymous component - use the "name" option for better debugging messages.)

不太清楚这个问题是什么意思,希望大神们给点解决办法,或者用其他路由方法也可以 只要跳转时不重复刷新页面就好。

还有个问题就是,vue-router 的history模式 说是需要后端配置否则会404 我按照官网的写法用node中间件把跳转路径都重新定向到当前页面了,虽然跳转是解决了,但是每次跳转都重新载入页面并不是局部刷新了 有什么解决办法吗?

阅读 19.1k
1 个回答

News引用的items应该是News这个组件的数据,而你的items是注册在根实例里的。

试试这样:

const News = {
    template:'<ul>\
                <li class="news" v-for="item in items">\
                    <div class="cover" v-bind:style="{backgroundImage:\'url(\'+item.bg+\')\'}"></div>\
                    <h4 class="title">{{ item.title }}<span class="up_time">{{ item.date }}</span></h4>\
                    <h5 class="detail">{{ item.detail }}</h5>\
                    <div class="border_bottom"></div>\
                </li>\
            </ul>\
',
    data: function () {
        return {
            items: []
        }
    }
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题