As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults.
The defaults object contains selectable options for social media links and their initial values. Essentially, I copy the default value into models and enable users to personalize the model through inputs.
data () {
return {
models : [] ,
defaults : {
twitter : { id : null , placeholder : 'my twitter' , icon : 'twitter' , text : null , 'link' : null } ,
instagram : { id : null , placeholder : 'my instagram' , icon : 'instagram' , text : null , 'link' : null } ,
tiktok : { id : null , placeholder : 'my tiktok' , icon : 'tiktok' , text : null , 'link' : null } ,
} ,
}
} ,
There is a select menu for users to choose which social media platform they want to add to the page.
Select :
<ul >
<li v-for="(social, index ) in defaults" :key="index">
<a @click="appendSocial(index)">
{{ index }}
</a>
</li>
</ul>
This is my
@click="appendSocial(index)"
function:
appendSocial(type){
let typedefault = this.defaults[type];
this.models.push(typedefault)
},
Finally, I display the models to the user and provide an input for editing its text using v-model
.
<div v-for="(model, index) in models" v-bind:key="model.id">
<a class="button-preview">
{{ model.text === null ? model.placeholder : model.text }}
</a>
<label>Text</label>
<input type="text" v-model="model.text" :key="index" :placeholder="model.placeholder">
</div>
The issue arises when changing properties in models or defaults changes the corresponding properties in the other object unexpectedly. For example, modifying the text of a Twitter link in models will also update the text in defaults.twitter.text.
To illustrate the problem, console logs have been added to the appendSocial function:
appendSocial(type){
let typedefault = this.defaults[type];
console.log(`-------- default object for ${type} -----------`);
console.log(typedefault);
this.addElement(typedefault);
},
Here are the results:
https://i.sstatic.net/U5gXN.png
1 - A Twitter link was selected and added to models, showing that defaults.twitter.text is null
2 - The text in model.text (assumed to be models[0].text) was changed to "abc"
3 - Another Twitter link was added, resulting in defaults.twitter.text also becoming "abc"
Moreover, modifying properties in defaults affects all models that initially received their values from that default object. For instance, changing defaults.instagram.text to "xyz" alters the text in all models derived from defaults.instagram to "xyz".
It seems like there is a reference between them, even though no value was passed by reference between the two objects. I am unsure of what is causing this behavior and how to prevent it?