4

I wonder if it is possible to load value of tag value as default value for vue.js data?

Works fine with

coupon: $('#coupon').val(),

but I really do not want to use jQuery.

Code is available here: https://jsfiddle.net/4a80dnfo/1/

1
  • Can we use v-scope here? Commented Mar 9, 2023 at 11:15

3 Answers 3

7

So I found a way to get this done using the beforeMount() hook.

Assuming this HTML:

<div id="coupon-code">
    <input ref="coupon" v-model="coupon" value="99PI_ORG" />
</div>

This Javascript should get the job done:

  new Vue({
    el: '#coupon-code',
    data: {
      coupon: ''
    },
    beforeMount: function() {
      this.coupon = this.$el.querySelector('[ref="coupon"]').value;
    }
    // methods and such here.
  }
});

I ended up using the beforeMount() hook after some trial an error. Some things I've learned which may be relevant:

  • this.$refs does not exist in the created() hook.
  • this.$refs.coupon.value returns an empty string in the mounted() hook.
  • The ref attribute of an element is deleted before the mounted() hook, so something like this.$el.querySelector('input[ref=coupon]') does not work.
  • You can use this.$el.querySelector('input[data-ref=coupon]').attributes['value'].value inside mounted(), but this seems worse to me than using beforeMount().

If anyone has suggestions on how to do this better, I'm very open to feedback. This solution still feels sub-optimal to me.

Sign up to request clarification or add additional context in comments.

Comments

6
<input  name="coupon"  v-model="coupon" value="def val">    

window.app = new Vue({
    el: '#xxx',
    data: {
       coupon: document.querySelector("input[name=coupon]").value
    }
    ...
});

1 Comment

While this might answer the question, a bit of explanation would not be bad.
6

In your jsfiddle you are using v-model, so in your data() you just have to set your desired value

Edit: updated code to use v-bind

new Vue({
    el: '#app',
    data: {
            coupon: 'You value here',
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>

<div id="app">
  <input id="coupon" type="text" name="coupon" :value="coupon" />
</div>

2 Comments

Yes, I know this way, but I would like to pass data from html tag value instead of set it in Vue. Is it possible?
@KMatko i updated the asnwer. Use the 'v-bind:' or shorthand for it ':', but take note that you cannot mix it with v-model as it will be defeating the whole purpose of v-model (two-way data binding).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.