我正在使用props
将对象的克隆从父组件传递到子组件,但是当我在父组件的对象中更改status
属性的值时,子组件得到通知并在“克隆的”对象中确定status
属性的值。
我已经了解了Object.assign()
方法,它只进行浅表复制,但是奇怪的是我的对象属性是原始类型 String ,这意味着它们应该按值复制而不是通过引用,我什至尝试手动分配值,并尝试使用JSON方式,如下所示,但没有任何效果。
父组件:AppServers
<template>
<div>
<AppServerStatus v-for="server in servers" :serverObj="JSON.parse(JSON.stringify(server))">
</AppServerStatus>
<hr>
<button @click="changeStatus()">Change server 2</button>
</div>
</template>
<script>
import AppServerStatus from './AppServerStatus';
export default {
name: "AppServers",
components: {
AppServerStatus
},
data() {
return {
servers: [
{
name: 'server1',
status: 'Critical'
},
{
name: 'server2',
status: 'Normal'
},
{
name: 'server3',
status: 'abnormal'
},
{
name: 'server4',
status: 'idle'
},
{
name: 'server5',
status: 'Good'
},
],
serverTmp: {}
}
},
methods: {
changeStatus(){
this.servers[1].status = 'Active';
}
}
}
</script>
子组件:AppServerStatus
<template>
<div>
<h3>Server Name: {{ serverObj.name }}</h3>
<p>Server Status: {{ serverObj.status }}</p>
<hr>
</div>
</template>
<script>
export default {
name: "AppServerStatus",
data() {
return {
status: 'Critical'
}
},
props: [
'serverObj'
]
}
</script>
当我在父组件中执行status
时,我希望子组件的对象中changeStatus()
属性的值保持 Normal ,但它也会改变。
答案 0 :(得分:2)
通过var id = 65352;
Swal.fire({
title: 'settings for project '+id,
html:
"<p>some setting</p>"+
"<input class='toggle' id='setting' data-docid='"+id+"' type='checkbox' checked>",
showCancelButton: true,
showConfirmButton: false,
cancelButtonText: 'close',
onBeforeOpen: () => {
const setting = $("#setting[data-docid="+id+"]");
$(setting).on("change",function(){
console.log($(this).attr("checked"));
if($(this).attr("checked") == "checked"){
$checked = 1;
}else{
$checked = 0;
}
$.parameters = {
id: id,
checked: $checked,
type: "accept"
}
//using an api to communicate between client and server
result = "TRUE"
if(result.indexOf("TRUE") > -1){
const Toast = Swal.mixin({ //when firing the toast, the first window closes automatically
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
Toast.fire({
type: 'success',
title: 'changed the thingy successfully'
})
}else{
const Toast = Swal.mixin({ //when firing the toast, the first window closes automatically
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
Toast.fire({
type: 'error',
title: 'cant change the thingy'
})
}
});
}
})
或<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.11.5/dist/sweetalert2.all.min.js"></script>
上的serverObj
道具创建一个新对象,以防止不必要的反应。
created