computed如何传参
computed: {
url() {
return function (param) {
return xxx + param;
};
},
}
//使用方法 <a :href="url(param)">删除</a>
关于路由传参刷新页面后数据丢失的解决方案(name+params)
//about.vue
<template>
<div class="about">
<h1>This is an about page</h1>
<el-button type="primary" icon="el-icon-share" @click="push"></el-button>
</div>
</template>
<script>
export default {
methods:{
push(){
this.$router.push({name:'paramsPush',params:{name:'hanpi',age:'22'}})
}
}
}
</script>
//paramsPush.vue
<template>
<div>
<el-tag type="info">{{paramf}}</el-tag>
<el-tag type="warning">{{params}}</el-tag>
</div>
</template>
<script>
export default {
data() {
return {
paramf: this.$route.params.name,
params: this.$route.params.age
};
}
};
</script>
上述两个组件,点击about.vue中的按钮跳转到paramsPush.vue,tag标签可以显示通过params传递的name和age,但是刷新的话页面数据就会丢失
解决方案一:
//router规则配置
//router/index.js
{
path: '/paramsPush/:name/:age',
name: 'paramsPush',
component: () => import('../views/paramsPush.vue')
},
//直接调用$router.push 实现携带参数的跳转
this.$router.push({
path: `/describe/${name}/${age}`,
})
//取值
this.$route.params.xxx
解决方案二:
//使用path+query传参来替代
//about.vue
<script>
export default {
methods:{
push(){
// this.$router.push({name:'paramsPush',params:{name:'hanpi',age:'22'}})
this.$router.push({path:'/paramsPush',query:{name:'hanpi',age:'22'}})
}
}
}
</script>
//paramsPush.vue
<script>
export default {
data() {
return {
// paramf: this.$route.params.name,
paramf: this.$route.query.name,
// params: this.$route.params.age,
params: this.$route.query.age
};
}
};
</script>
解决方案三:
//使用localStorage存在本地
//paramsPush.vue
<script>
export default {
data() {
return {
paramf: this.$route.params.name,
// paramf: this.$route.query.name,
params: this.$route.params.age
// params: this.$route.query.age
};
},
created() {
let paramsData = JSON.parse(localStorage.getItem("params"));
window.console.log(paramsData)
if (paramsData) {
this.paramf = paramsData.name;
this.params = paramsData.age;
} else {
localStorage.setItem("params", JSON.stringify(this.$route.params));
}
},
destroyed() {
localStorage.removeItem("params");
}
};
</script>