gpt4 book ai didi

javascript - 如何将 Vue 属性设置为字符串化元素属性的值?

转载 作者:行者123 更新时间:2023-11-30 14:28:32 26 4
gpt4 key购买 nike

请原谅我这个愚蠢的问题。

我有这样的东西:

var app = new Vue({
el: '#app',
data: {
words: []
},
created() {
let something = document.getElementById('word_data')
if (something) { this.words = something.dataset.content.slice() }
}
})

这是 HTML 部分:

<input type="hidden" id="word_data" data-content="[&quot;one&quot;,&quot;two&quot;,&quot;thee&quot;]">

这只是一个格式为 ["one", "two", "three", "four", "etc"] 的数组。

我正在尝试将此数组分配给 Vue 中的 words。我该怎么做?

如果我按照示例中的方式分配它,它将把整个数组作为单个记录。

我敢肯定这很简单。我错过了什么?

最佳答案

只需获取元素的 data-content 属性值,然后使用 JSON.parse() 将其从您提供的格式进行转换。

var app = new Vue({
el: '#app',
data: {
words: []
},
created() {
const element = document.getElementById('word_data');
const data = JSON.parse(element.getAttribute('data-content'));
if (data) { this.words = data }
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<input type="hidden" id="word_data" data-content="[&quot;one&quot;,&quot;two&quot;,&quot;thee&quot;]" >

<div id="app">
<ul>
<li v-for="word in words">{{word}}</li>
</ul>
</div>

关于javascript - 如何将 Vue 属性设置为字符串化元素属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com