Home > Software design >  How to use map() in vue.js 2
How to use map() in vue.js 2

Time:11-26

Im start learning vue.js and ive got some troubles. I need to use dictionary analog in js. Its called map. but i dont know where i should define it. I need to use it in checkDevices() method and in HTML code

P.S. Sorry for my English

export default {
    data: () => ({
   }),
   devicesList: new map(
    "varNameOne", false,
    "varNameTwo", false,
    "varNameThree", false,
    ),
    methods: {
        async checkDevices () {
            let response = await axios.get(`/some/api`)
            console.log("res.data: ", response.data);

            devicesList.forEach((values, keys) => {
            console.log("Key: ", keys, "Value: ", values);
            })
        }
    }
}

ive trying to define it before export default like this: let devicesList = new map(...);, but it doesnt work.

In axios.get(`/some/api`) ive got response frome server with data (response.data):

device1: true
device2: false
device1: true 

I need take it frome response in key-value pair for using in UI like

  • device1 connected
  • device2 disconnected
  • divice3 connected

CodePudding user response:

I don't know the JSON of your Axios response so you need to update checkDevices function to match the key values. there is no need to use map above export default. you can do this in mounted function.

export default {
    data:function(){
        return {
            devicesList:[]
        }
    },
    mounted:function(){
        this.devicesList = new Map();
        this.devicesList.set('device1', false);
        this.devicesList.set('device2', false);
        this.devicesList.set('device3', false);
    },
    methods: {
        async checkDevices () {
            let response = await axios.get(`/some/api`)
            console.log("res.data: ", response.data);

            devicesList.forEach((values, keys) => {
                console.log("Key: ", keys, "Value: ", values);
                //Please Use YOUR RESPONSE.data here to update the device List
            })
        }
    }
}
  • Related