I'm updating some Vue 3 components to use the new Composition API.
The code needs to be able to run inside the new .
I'm still learning, and I couldn't find an example of how to do it on the internet.
Thanks in advance!
export default {
data() {
return {
productName: '',
productFeatures: '',
temperature: 0.1,
generatedText: '',
loading: false,
aviso: false
}
},
methods: {
generateText() {
this.loading = true;
let prompt = `This is a test ${this.productName}.`;
axios.post('https://example.com', {
model: "XXXXXX",
logprobs: 1,
max_tokens: 500,
prompt: prompt,
temperature: 0.3
// temperature: 0.7,
}, {
headers: {
'Authorization': 'Bearer XXXXXXXXXXXXX'
}
}).then(response => {
this.generatedText = response.data.choices[0].text;
this.loading = false;
this.aviso = true;
});
}
}
}
CodePudding user response:
Here is an example how you can translate it to composition API way. You still need to learn how Vue 3 work.
<script setup>
const {
productName,
productFeatures,
temperature,
generatedText,
loading,
aviso
} = reactive({ productName: '', productFeatures: '', temperature: 0.1, generatedText: '', loading: false, aviso: false })
function generateText() {
loading = true;
let prompt = `This is a test ${productName}.`;
axios.post('https://example.com', {
model: "XXXXXX",
logprobs: 1,
max_tokens: 500,
prompt: prompt,
temperature: 0.3
}, {
headers: {
'Authorization': 'Bearer XXXXXXXXXXXXX'
}
}).then(response => {
generatedText = response.data.choices[0].text;
aviso = true;
}).finally(() => loading = false);
}
</script>
I changed the place where loading value is changing to false in a function because if you have an error it will load end less.
Instead of reactive()
you can use ref()
like this:
<script setup>
const productName = ref('')
const productFeatures = ref('')
const temperature = ref(0.1)
const generatedText = ref('')
const loading = ref(false)
const aviso = ref(false)
function generateText() {
// Using ref instead of reactive means you need to get
// values by .value and same way assign them.
loading.value = true
...
}
</script>
Ref<T>
are for simple variables, not objects. They will work correct when you assign something direct to .value = "bla"
but no, if it is an object, and you want to update value inside of that object .value.title = "bla"
. Ref<T>
won't know that you updated .title
value, so you lose reactivity your template won't update title.
You won't lose reactivity if you use Ref<T>
like this:
const data = ref({ title: "Some title" })
data.value = { ...data.value, title: "Some new title" }
Read about what ...
spread operator do if you don't know.