Skip to content

使用HTML data‐*属性传递参数

oldbird edited this page Aug 4, 2023 · 3 revisions

我们可以使用data-*来嵌入自定义的数据,比如添加评论的时候,需要传递文章id:

 <div class="flex flex-col mt-8">
      <textarea x-model="addedComment.content"  class="textarea textarea-accent textarea-lg w-ful"  placeholder="发表评论"></textarea>
      <div class="flex flex-row justify-end">
          <button data-id="#(data.id)" @click="addComment" class="btn bg-primary w-32 mt-4">发表评论</button>
      </div>
</div>

通过data-id="#(data.id)",表示将文章的id赋值了给data-id属性.

addComment的方法中可以通过下面的方式获取到这个值:

async function addComment(e) {
   var topicId = e.currentTarget.dataset.id;
   //...
}

data-*只支持字符串传递,如果我们想传递对象,我们可以把对象先转换成字符串类型,转递过去之后再转换成对象。