I have a very simple task i am trying to solve. I want to make the vue model update or display in a new property called chunk2 when there is a change. I am sending the value back to using this.chunk=this.chunk2. How can I achieve this. The result after the button is clicked should say "This is a chun"..in which the "k" gets removed.
new Vue({
el: "#app",
data: {
chunk:"this is a chunk",
chunk2:"",
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
},
methods: {
toggle: function(){
this.chunk.split('n')[1];
alert(this.chunk.split('n')[1]);
this.chunk=this.chunk2
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
{{chunk}}
{{chunk2}}
<br>
<button v-on:click="toggle()">magic
</button>
</div>
CodePudding user response:
Observations :
- Strings are immutable. Hence, The string manipulation methods such as split returns a new array and will not update the original string. Ex :
let chunk = 'this is a chunk';
const newStr = chunk.split('n');
console.log(chunk); // this is a chunk (Not changing the original string)
console.log(newStr); // updating the maniupulated values in a new variable.
- As
chunk2is an empty string and you are assigning it back intochunkwill updatechunkalso empty. this.chunk.split('n')will split the string with excludingn. Hence, If you want to includen. You have to split it withk.
Working Demo :
new Vue({
el: "#app",
data: {
chunk:"this is a chunk",
chunk2:"",
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
},
methods: {
toggle: function(){
this.chunk = this.chunk.split('k')[0];
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
{{chunk}}
{{chunk2}}
<br>
<button v-on:click="toggle()">magic
</button>
</div>
