携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情
data-*属性是HTML5中增加的元素全局属性,它能让我们在所有HTML元素上嵌入自定义数据属性的能力,并且通过js来获取,在Vue的template代码里边用data-变量名使用:
<text data-title="你好,掘金" @click="postParams">你好,掘金</text>
data-*的自定义属性名可以任意命名,但必须遵循名称全部小写,并且不能包含任何分号。
data-*通过Js事件可以在dataset中拿到数据:
postParams(e) {
console.log(e.currentTarget.dataset.title);
}
下面通过例子,来实现以下使用data-*进行页面之间的传参,首先建立两个page页面postPage和receivePage,用于发送和接收参数,在postPage中,放入一个文章列表,并注册@click事件:
<template>
<view class="main">
<view v-for="(item,index) in newsList" :key="index" class="news" :data-title="item.title" :data-id="item.id"
@click="goInfo">
<text>{{item.title}}</text> <text>{{item.author}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
newsList: [{
id: 1,
title: "uni-app开发-App版本检测与下载",
author: "沈麽鬼"
}, {
id: 2,
title: "uni-app开发-uni-app页面通信方法集锦",
author: "沈麽鬼"
}, {
id: 3,
title: "uni-app开发-底部菜单",
author: "沈麽鬼"
}, {
id: 4,
title: "uni-app开发-顶部导航栏",
author: "沈麽鬼"
}, {
id: 5,
title: "uni-app开发-启动页",
author: "沈麽鬼"
}, {
id: 6,
title: "uni-app开发-本地存储",
author: "沈麽鬼"
}]
}
},
methods: {
/**
* 跳转到详情页
* @param {Object} e
*/
goInfo(e) {
localStorage.setItem('title', e.currentTarget.dataset.title)
localStorage.setItem('id', e.currentTarget.dataset.id)
uni.navigateTo({
url: '/pages/params/receivePage'
})
}
}
}
</script>
<style>
.main {
padding: 30rpx;
}
.news {
display: flex;
justify-content: space-between;
line-height: 60rpx;
border-bottom: 1px saddlebrown solid;
}
</style>
当点击列表时,通过localStorage的方法,将data-title和data-id保存的数据进行存储,并进行跳转,在receivePage接收页,在onLoad生命周期中,即可拿到两个数据:
<template>
<view class="main">
{{title}}
{{id}}
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
this.title = localStorage.getItem('title')
this.id = localStorage.getItem('id')
},
methods: {
}
}
</script>
<style>
.main {
text-align: center;
}
</style>
\