local.js
function getLocalstorage (name) {
const res = JSON.parse(window.localStorage.getItem(name)) || []
return res
}
/**
*
* @param {*} name 对象键名
* @param {*} content 对象值
* @param {*} that 将调用的组件对象传递进来,用来触发 $message
*/
function setLocalstorage (name, content, that = false) {
window.localStorage.setItem(name, JSON.stringify(content))
that && that.$message.success('新增成功')
}
export {
getLocalstorage,
setLocalstorage
}
<template>
<div>
<h1 ref="name">{{ name }}</h1>
<button @click="changeName" @contextmenu.prevent.stop="rightClick($event)">
修改name
</button>
</div>
</template>
<script>
import { getLocalstorage, setLocalstorage } from '../../utils/local'
export default {
data () {
return {
name: 'vue2'
}
},
created () {
this.name = getLocalstorage('person')
},
methods: {
changeName () {
const person = {
name: '张三',
age: 20
}
const that = this
setLocalstorage('person', person, that)
},
rightClick (e) {
console.log(e)
}
}
}
</script>
<style>
</style>
简易table组件
父组件:
<template>
<child :arr="state.arr">
<template #btns="{row}">
<button @click="hdClick(row)">编辑</button>
<button @click="deleteFn(row)">删除</button>
</template>
</child>
</template>
<script lang='ts' setup>
import { reactive } from "vue"
import child from './child.vue'
let state = reactive({
arr: [{
name: "1",
age: 18
}, {
name: "2",
age: 20
},
{
name: "3",
age: 18
}, {
name: "4",
age: 20
}]
})
interface RowItf {
name: string,
age: number,
index: number
}
const hdClick = (row: unknown) => {
console.log(row);
}
const deleteFn = (row: any) => {
let index = state.arr.findIndex(item=>{
return item.name == row.name
})
state.arr.splice(index, 1)
}
</script>
<style lang = "less" scoped></style>
子组件:
<template>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<tr v-for="(item, index) in arr" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<slot name="btns" :row="item"></slot>
</td>
</tr>
</table>
</template>
<script lang='ts' setup>
import { } from "vue"
let props = defineProps({
arr: {
type: Array,
default: () => []
}
})
props.arr.forEach((item: any, index) => {
item.index = index
})
</script>
<style lang = "less" scoped></style>