javascriptvue.jsyandex-maps

How to export data from javascript in vuejs?


I have a vuejs form and a pure JS-based map widget. I need to extract coords from map (vanilla js) into form input (vuejs). How can I do that? View:

<el-form :model="storeForm" label-width="200px" ref="storeForm" status-icon size="small">
    <el-form-item label="Address" prop="Address">
        <el-input v-model="storeForm.Address" type="textarea"></el-input>
    </el-form-item>
    <el-form-item>
        <div id="map" style="width: 600px; height: 400px"></div>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="save('storeForm')">Save</el-button>
        <el-button @click="cancel()">Cancel</el-button>
    </el-form-item>
</el-form>

And a vuejs code:

export default {
    data() {
        return {
            isNew: true,
            storeForm: {
                Address: ''
            }
        }
    },
    created() {
        ymaps.ready(function () {
            var map = new ymaps.Map("map", {
                center: [43.241203, 76.957206],
                zoom: 13
            });

            map.events.add('click', (e) => {
                var coords = e.get('coords');

                //obviously that doesn't work
                this.storeForm.Address = e.get('coords');
            });
        });
    }
}

Solution

  • The line

    ymaps.ready(function () {

    creates a new scope, so this is no longer your Vue app.

    Replace with

    ymaps.ready(() => {

    Or add .bind(this) at the end of that function.