javascript - vue 在template 写 v-for 问题

查看:282
本文介绍了javascript - 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中间件把跳转路径都重新定向到当前页面了,虽然跳转是解决了,但是每次跳转都重新载入页面并不是局部刷新了 有什么解决办法吗?

解决方案

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: []
        }
    }
},

这篇关于javascript - vue 在template 写 v-for 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆