Pyreal
Pyreal

Reputation: 517

How do I change the value of a textarea when using a reuseable component?

I need to change the text within a specific component's textarea when requirements are met from entering text into a different components textarea. I've tried to create a simple example to show the issue. my main issue is targeting the correct component and editing its text that shows up dynamically.

Parent Component

<template>
    <reuseableComponent 
        input-type="textarea" v-model="Example1">
    </reuseableComponent>
    <reuseableComponent 
        input-type="textarea" v-model="Example2">
    </reuseableComponent>
<template>

Reuseable Component

<textarea
    v-model='taValue' @input='$emit("input", taValue)'>
</textarea>

exampleMethod() {
    if(value) {
        //change text in Example2 textarea instance.
    }
}

Upvotes: 5

Views: 19053

Answers (1)

ironcladgeek
ironcladgeek

Reputation: 1130

If I got it right, you are trying to change the second component's value if the first component's value matches a certain criteria. So, If that's the case, I have produced a working fiddle that you may find it here, which by typing Foo in first reusable textarea you will get Bar in second textarea.

window.Event = new Vue();

Vue.component('my-textarea', {
	template: `
  	<textarea :value="value" 
    		  @input="updateValue($event.target.value)" 
                 :placeholder="placeholder"
    		  ref="input"
    >
    </textarea>`,
  props: {
  	value: { default: '' },
        placeholder: { default: '' }
  },
  methods: {
  	updateValue(value) {
      // adding v-model support to this reusable component
      this.$refs.input.value = value;
      this.$emit('input', value);
          
       // Firing an event via Event bus to notify sibling reusable component
       Event.$emit('valueChanged', this._uid, value);
     }
  },
  
  mounted() {
        // Listening for 'valueChanged' event
  	Event.$on('valueChanged', (id, value) => {
    	if (id != this._uid) {
      	    if (value === 'Foo') {
        	this.$refs.input.value = 'Bar';
        }
      }
    }); 
  }
  
});

new Vue({
  el: '#app',
  data() {
      return {
    	text1: '',
        text2: ''
    }
  }

});
<div id="app">
  <my-textarea v-model="text1" placeholder="Type Foo here"></my-textarea>
  <my-textarea v-model="text2"></my-textarea>
</div>

https://jsfiddle.net/mrzerehpoosh/Lnkrjqy6/

Upvotes: 5

Related Questions