Vue中循环出现is not defined无法取出数据

爱蜜莉雅
  • 253

初学前端,在学习vue时遇到如下问题:
这边需要两个List,两个List显示不同内容,我打算用两个for循环解决这个问题。
然后我写了如下代码,第一个list正常显示,第二个出了错不显示。

Html

<div id="list">
    <ul>
        <li v-for="searchItem in searchItems">
            <a :href="searchItem.url">{{ searchItem.name }}</a>
        </li>
    </ul>
    <ul>
        <li v-for="mailItem in mailItems">
            <a :href="mailItem.url">{{ mailItem.name }}</a>
        </li>
    </ul>
</div>

js

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    var one = new Vue({
        el: "#list",
        data: {
            searchItems: [
              { name: 'Baidu', url: 'https://www.baidu.com' },
              { name: 'Bing', url: 'https://www.bing.com' },
              { name: '360', url: 'https://www.so.com' }
            ]
        }
    });
    
    var two = new Vue({
        el: "#list",
        data: {
            mailItems: [
              { name: '126', url: 'https://www.126.com/' },
              { name: '163', url: 'https://www.163.com/'},
              { name: 'Yeah', url: 'https://www.yeah.net/'}
            ]
        }
    });
</script>

错误提示

vue.js:634 [Vue warn]: Property or method "mailItems" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)

不知道哪里出错了,两个Vue分别注释其中一个也都能正常运行,然后自己也尝试了很多方法也没能解决,还请大家帮忙看一下,谢谢!

回复
阅读 5.8k
3 个回答
✓ 已被采纳

报错的意思是你这个mailItems没有在data中定义,却在render中使用了。
因为你new了俩Vue,而且el还指向的是一样的。
可以把第二个数组放到第一个Vue实例里

比如

var one = new Vue({
        el: "#list",
        data: {
            searchItems: [
              { name: 'Baidu', url: 'https://www.baidu.com' },
              { name: 'Bing', url: 'https://www.bing.com' },
              { name: '360', url: 'https://www.so.com' }
            ],
            mailItems: [
              { name: '126', url: 'https://www.126.com/' },
              { name: '163', url: 'https://www.163.com/'},
              { name: 'Yeah', url: 'https://www.yeah.net/'}
            ]
        }
    });

你不能同时创建两个vue实例,应该这样写

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    var one = new Vue({
        el: "#list",
        data: {
            searchItems: [
              { name: 'Baidu', url: 'https://www.baidu.com' },
              { name: 'Bing', url: 'https://www.bing.com' },
              { name: '360', url: 'https://www.so.com' }
            ],
            mailItems: [
              { name: '126', url: 'https://www.126.com/' },
              { name: '163', url: 'https://www.163.com/'},
              { name: 'Yeah', url: 'https://www.yeah.net/'}
            ]
        }
    });   
</script>

new Vue的使用不要使用同一个el

宣传栏