[Vuejs]-Why does old value not passed to vue component?

1๐Ÿ‘

โœ…

You have to define a prop and set the data to that prop

When you pass data in a component tag via the v-bind shorthand : these data are known as props and have to be defined as such

Vue disallows mutating props passed from the parent in the child, therefor you should make a local copy of that prop in the reactive data object

props: {
    queryProp: {
        required: false,
        type: String
    }
},
data() {
    return {
        results: [],
        query: this.queryProp
    };
},

Assuming a Blade view like so

<div id="app">
    <form action="/" method="post">
        @csrf
        <input type="text" name="regionName"> <br>
        <button type="submit">Submit</button>
    </form>
    <autocomplete-region-component :query-prop="{{ json_encode(old('regionName')) }}"></autocomplete-region-component>
</div>

<script src="/js/app.js"></script>

And routes like so

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::view('/', 'welcome');
Route::post('/', fn (Request $request) => $request->validate(['regionName' => 'integer']));

This is what you would get if invalid data is posted
enter image description here

2๐Ÿ‘

When you create a component (like you have with <autocomplete-region-component>, if you want to pass values to it from itโ€™s parent, you have to define the prop at the component level. So in your script, add a props property like so:

    props: [
        'query',
    ],

Now in your autocomplete-region-component component, you can use the value of query as this.query as you would expect.

In your component tag, you donโ€™t use mustache tags to pass the value, you would just pass normal javascript. Iโ€™d also recommend not encoding the json at that point. You could always encode it within the component if you needed to.

<autocomplete-region-component :query="old('regionName')"> 
</autocomplete-region-component>

1๐Ÿ‘

Mustache syntax is to interpolate text, not to pass props.

To pass props or set attributes to child components (including native HTML elements), you need to use v-bind directive (doc).

<a> element is good to remember this rule.

<a :href="myUrl">{{ linkText }}</a>

Then, your code should look like this:

<autocomplete-region-component :query="json_encode(old('regionName'))"> 
</autocomplete-region-component>

Leave a comment