从Vue实例html标记传递数据属性

问题描述 投票:0回答:2

是否可以从Vue实例的html标记声明并传递数据属性值,然后在数据对象中使用它?

index.html的:

<div id="app" data-title="My app title"></div>

App.vue:

data () {
  return {
    appTitle: // whatever is declared in data-title
  }
}
vue.js
2个回答
1
投票

是的:

data () {
  return {
    appTitle: document.getElementById('app').dataset.title
  }
}

但是,有可能DOM在组件初始化时不可用。所以你应该将代码放入组件的挂钩中:

<script>
    export default {
        data () {
            return {
                appTitle: null
            }
        },
        mounted () {
            this.appTitle = document.getElementById('app').dataset.title
        }
    }
</script>

0
投票

这是一种不依赖于DOM API的不同方法,但不能用于从根(#app)元素获取数据属性:

{
    el: '#app',
    template: `
        <div ref="mydiv" data-attribute="data attribute">
            Hello from template
            <div>
                Hello from {{attribute}}
            </div>
        </div>`,
    data(){
        return {
          attribute: ''
        }
    },
    mounted(){
        this.$data.attribute = this.$refs.mydiv.dataset.attribute;
    }
});

Here's a pen with a working example


0
投票

这段代码适合我:

index.html的:

<div id="app" data-id="123"></div>

index.js:

(function (el) {

    new Vue({
        el,
        render: h => h(Module),
        data: () => Object.assign({}, el.dataset) ,
    });

})(document.getElementById('app'));

Module.vue:

export default {
    name: 'Module',
    data() {
        return {
            id: this.$parent.id,
        };
    },
};
© www.soinside.com 2019 - 2024. All rights reserved.