其中settings
是assest
文件夹中的json, 经过log方法后源文件被改变了。
import vuedraggable from 'vuedraggable'
import RenderString from './RenderString'
import { mapState, mapMutations } from 'vuex'
import settings from '@/assets/settings.json'
export default {
name: 'ShowArea',
components: {
vuedraggable,
RenderString
},
data () {
return {
list: [],
active: -1
}
},
computed: {
...mapState({
attrs: state => state.attrs
})
},
methods: {
selected (item, index) {
this.active = index
},
log (t) {
for (let i in t) {
this.active = t[i].newIndex
const item = this.list[this.active]
if (i === 'added') {
const d = window.Object.assign({}, settings[item.name], { name: item.name })
console.log(settings) // 这个json文件内容被改变了
const arr = this.attrs
arr.splice(this.active, 1, d)
this.setAttrs(arr)
}
}
},
...mapMutations({
setAttrs: 'changeAttrs',
setActiveAttrs: 'setActiveAttrs'
})
},
watch: {
active () {
this.setActiveAttrs(this.active)
}
}
}
</script>
如
a
的变量值将不会改变,因为a
是基本类型因为
ab
是引用类型
,赋值不是简单的赋值数据,而是赋值内存地址,因为b和a的地址指向一个地方,所以b改变了,a也会变.使用JSON.stringify和JSON.parse可以解决问题
给vue搞个clone方法
使用JSON.parse(JSON.stringify)方法转换为基本类型再转换成引用类型,确实可以改变原引用的内存地址达到复制克隆的效果, 然而源对象何时改变的,无法得知。