Vue里set方法的应用

一、应用在数组上
如下例中,是要实现vm.items[1] = ‘excess’

<body>
<div id="app">
    <ul>
        <li v-for="(item, index) in items">
            {
    
    {
    
     index }} : {
    
    {
    
     item }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    
    
    el: '#app',
    data: {
    
    
        items: ['a', 'b', 'c']
    },
    created() {
    
    
        this.$set(this.items, 1, 'excess')
    }
})
</script>
</body>

二、应用在对象上
如下例中,是要实现给object新增一个键值对{test: ‘newthing’}

<body>
<div id="app">
    <ul>
        <li v-for="(value, name) in object">
            {
    
    {
    
     name }} : {
    
    {
    
     value }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    
    
    el: '#app',
    data: {
    
    
        object: {
    
    
            title: 'How to do lists in Vue',
            author: 'Jane Doe',
            publishedAt: '2016-04-10'
        }
    },
    created() {
    
    
        this.$set(this.object, 'test', 'newthing')
    }
})
</script>
</body>

转载自https://segmentfault.com/a/1190000021636720

おすすめ

転載: blog.csdn.net/weixin_46353030/article/details/119351380